package com.ilibrary.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

import com.ilibrary.base.MyBaseVO;
import com.ilibrary.constants.MyMsgConstants;
import com.ilibrary.db.dao.hibernate.AdminDao;
import com.ilibrary.db.entity.Admin;
import com.ilibrary.service.AdminService;
import com.ilibrary.web.dto.ResultDto;
import com.ilibrary.web.vo.AdminVO;

public class AdminServiceImpl implements AdminService {
	
	private AdminDao adminDao;
	
	public AdminDao getAdminDao() {
		return adminDao;
	}
	public void setAdminDao(AdminDao adminDao) {
		this.adminDao = adminDao;
	}

	@Override
	public ResultDto<AdminVO> findAll() {
		ResultDto<AdminVO> resultDto = new ResultDto<AdminVO>();
		AdminVO adminVO = null;
		List<Admin> adminList = adminDao.findAll();
		for (Admin admin : adminList) {
			adminVO = new AdminVO();
			try {
				BeanUtils.copyProperties(admin, adminVO);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			resultDto.addToResultList(adminVO);
		}
		resultDto.setSuccess(true);
		return resultDto;
	}
	
	@Override
	public ResultDto<AdminVO> findById(String userId) {
		ResultDto<AdminVO> resultDto = new ResultDto<AdminVO>();
		AdminVO adminVO = new AdminVO();
		Admin admin = adminDao.findById(userId);
		if(admin != null) {
			try {
				BeanUtils.copyProperties(adminVO, admin);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			resultDto.addToResultList(adminVO);
			resultDto.setSuccess(true);
		}else {
			resultDto.setSuccess(false);
			resultDto.setMsg(MyMsgConstants.LOGIN_ERROR_INVALID);
		}
		return resultDto;
	}
	
	@Override
	public ResultDto<MyBaseVO> update(AdminVO orgAdminVO) {
		ResultDto<MyBaseVO> resultDto = new ResultDto<MyBaseVO>();
		Admin admin = new Admin();
		try {
			BeanUtils.copyProperties(admin, orgAdminVO);
			adminDao.update(admin);
		} catch (IllegalAccessException e) {
			resultDto.setSuccess(false);
			resultDto.setMsg(MyMsgConstants.UPDATE_EXCEPTION);
			e.printStackTrace();
			return resultDto;
		} catch (InvocationTargetException e) {
			resultDto.setSuccess(false);
			resultDto.setMsg(MyMsgConstants.UPDATE_EXCEPTION);
			e.printStackTrace();
			return resultDto;
		}
		resultDto.setSuccess(true);
		return resultDto;
	}

}
